#!/usr/bin/env python3

import datetime
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
from factors.sizef import SizeFactor
from factors.industryf import IndustryFactor
from factors.roef import RoeFactor

matplotlib.use("MacOSX")
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
sns.set_style('darkgrid')

def roe_stock_lineplot(roe_ttm, stock_code, since, save=False):
    query_expr = f"STOCK_CODE=='{stock_code}' & I_RPT_PERIOD > '{since}'"
    stock_roe_ttm_11y = roe_ttm.query(query_expr)
    sns.set_theme(style="darkgrid")
    g = sns.relplot(x="I_RPT_PERIOD", y="ROE_TTM", kind="line",
                    data=stock_roe_ttm_11y, height=6, aspect=3)
    g.figure.autofmt_xdate()
    if save:
        suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
        g.figure.savefig(f'{stock_code}_{since}_{suffix}.png')
    plt.show()

def roe_stock_histplot(roe_ttm, stock_code, since, save=False):
    query_expr = f"STOCK_CODE=='{stock_code}' & I_RPT_PERIOD > '{since}'"
    stock_roe_ttm_11y = roe_ttm.query(query_expr)
    sns.set_theme(style="darkgrid")
    g = sns.histplot(stock_roe_ttm_11y["ROE_TTM"], bins=30, kde=True)
    g.figure.autofmt_xdate()
    if save:
        suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
        g.figure.savefig(f'{stock_code}_{since}_{suffix}.png')
    plt.show()

def sizef_plot(qd, save=False):
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
    fig.set_figwidth(18)
    fig.set_figheight(5)
    sfactor = SizeFactor(qd)
    # sns.displot(dat, )
    sns.histplot(sfactor.dat, bins=30,
                 kde=True, ax=ax1)
    # cfactor = CatFactor(qd)
    rfactor = RoeFactor(qd)
    # -10321667000.0
    # income_data_sep["NET_PROFIT_GM"] = income_data_sep["NET_PROFIT_GM"].add(10321667000.0 + 1)
    # print(income_data_sep.nlargest(6, "NET_PROFIT_GM"))
    # print(np.histogram(np.log(income_data_sep["NET_PROFIT_GM"])))
    income_sep_dat = rfactor.sep_data.query('NET_PROFIT_GM > 1')
    print(rfactor.sep_data.shape)
    sns.histplot(np.log(income_sep_dat["NET_PROFIT_GM"]), bins=30,
                 kde=True, ax=ax2)
    print(rfactor.mrt_latest.shape)
    sns.histplot(rfactor.mrt_latest["MONTHLY_RETURN"], bins=30,
                 kde=True, ax=ax3)
    if save:
        suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
        fig.savefig(f'sizeln_incomeln_mrt_20210930.png')
    plt.show()
